package com.kaver.feign.rpc.eureka;

import java.util.Collection;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: EurekaAppCache
 * @Description: eureka实例缓存
 * @author kaver
 * @date 2019年5月29日 下午3:32:38
 * 
 */
public class EurekaAppCache {

	private static Map<String, Map<String, EurekaAppInstance>> EUREKA_APP_CACHE = new ConcurrentHashMap<>();
	
	public static Map<String, Map<String, EurekaAppInstance>> getCache(){
		return EUREKA_APP_CACHE;
	}
	
	public static void add(String appName, String instanceId, EurekaAppInstance appInstance) {
		Map<String, EurekaAppInstance> appInstances = EUREKA_APP_CACHE.get(appName);
		if (appInstances == null) {
			appInstances = new ConcurrentHashMap<>();
		}
		appInstances.put(instanceId, appInstance);
	}

	public static Map<String, EurekaAppInstance> getAppInstances(String appName) {
		return EUREKA_APP_CACHE.get(appName);
	}

	public static EurekaAppInstance getCacheRandomEurekaAppInstance(String appName) {
		Map<String, EurekaAppInstance> appInstances = getAppInstances(appName);
		return randomEurekaAppInstance(appInstances);
	}

	public static EurekaAppInstance getRealRandomEurekaAppInstance(String appName) {
		EurekaAppInstance appInstance = getCacheRandomEurekaAppInstance(appName);
		if (appInstance == null) {
			Map<String, EurekaAppInstance> appInstances = EurekaApi.getAppInstance(EurekaServiceFactory.getEurekaUrl(),
					appName);
			EUREKA_APP_CACHE.put(appName, appInstances);
			return randomEurekaAppInstance(appInstances);
		}
		return appInstance;
	}

	public static EurekaAppInstance randomEurekaAppInstance(Map<String, EurekaAppInstance> appInstances) {
		if (appInstances == null || appInstances.isEmpty()) {
			return null;
		}
		Collection<EurekaAppInstance> collection = appInstances.values();
		Object[] instances =  collection.toArray();
		int length = instances.length;
		if (length == 1) {
			return (EurekaAppInstance) instances[0];
		}
		Random random = new Random();
		return (EurekaAppInstance) instances[random.nextInt(length)];
	}
	public static void main(String[] args) {
		Random random = new Random();
		System.out.println(random.nextInt(2));
	}
}
